package com.toolbox.excelexport

import com.toolbox.utils.DateUtil
import net.sf.jxls.exception.ParsePropertyException
import net.sf.jxls.transformer.XLSTransformer
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.openxml4j.exceptions.InvalidFormatException
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.http.HttpServletResponse

class Export {

    /**
     * 根据模板 将信息 导入到excel 中
     * @param response
     * @param dataList  将要导入到exel中 数据，已List 存储
     * @param downloadFileName 下载的exel文件的名称
     * @param inputStream  读取指定资源的输入流。
     * @throws Exception
     */

    public static void  export(HttpServletResponse response,@SuppressWarnings("rawtypes") List dataList,String downloadFileName,InputStream inputStream) throws Exception{
        Logger logger=LoggerFactory.getLogger(Export.class)
        response.reset();
        response.setContentType("application/msexcel");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;  filename=\"" +downloadFileName + "\"");
        logger.info("=======================================下载的exel文件的名称:"+downloadFileName)
        HSSFWorkbook hssfWorkbook = null;
        OutputStream outputStream=null
        Map<String,  Object> dataListMap = new HashMap<String, Object>();
        if(dataList != null){
            dataListMap.put("dataList", dataList);
//            logger.info("=================================导入到exel中数据dataList:"+dataList)
            dataListMap.put("currentDate", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
            XLSTransformer transformer = new XLSTransformer();
            try {
                hssfWorkbook = (HSSFWorkbook) transformer.transformXLS(inputStream, dataListMap);
                outputStream = response.getOutputStream();
                hssfWorkbook.write(outputStream);
            } catch (ParsePropertyException e) {
                e.printStackTrace();
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }finally{
                if(inputStream!=null){
                    inputStream.close();
                }
                if(outputStream!=null){
                    outputStream.close();
                }
            }
        }
    }
}
